import os
import datetime
import logging

async def save_mp3_file(audio_data, folder='answer_audio_records', audio_format='mp3'):
    try:
        if not os.path.exists(folder):
            os.makedirs(folder)
        current_time = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"{current_time}.{audio_format}"
        file_path = os.path.join(folder, filename)

        # 检查文件是否已存在，如果存在则增加一个递增的数字
        i = 1
        while os.path.exists(file_path):
            file_path = os.path.join(folder, f"{current_time}_{i}.{audio_format}")
            i += 1

        with open(file_path, 'wb') as f:
            f.write(audio_data)
        logging.info(f"Audio file saved as {file_path}")
        return file_path
    except Exception as e:
        logging.error(f"Error in save_mp3_file: {e}")

# 使用示例
# audio_data = b'...'  # 假设这是你的音频数据
# save_mp3_file(audio_data)